package com.xqq.listener;



import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import static com.xqq.utils.Constants.DATA_TYPE_LOCATION;
import static com.xqq.utils.Constants.DATA_TYPE_MESSAGE;
import static com.xqq.utils.Constants.MESSAGE_SAFE;
import static com.xqq.utils.Constants.MESSAGE_SOS;

@Slf4j
@Component
public class BdDataQueueListener {



//    @RabbitHandler
//    @RabbitListener(queues = "${spring.rabbitmq.queue-name}")
    public void handleData(String json, Channel channel, Message message) {
//        log.info("收到消息: {}", json);
        try {
            JSONObject jsonObject = JSONUtil.parseObj(json);
            int type = jsonObject.getInt("type");
            String data = jsonObject.getStr("data");
            // 根据数据类型进行处理
            switch (type) {
                // 处理位置数据
                case DATA_TYPE_LOCATION:
                    handleLocationData(data);
                    break;
                // 处理消息数据
                case DATA_TYPE_MESSAGE:
                    handleMessageData(data);
                    break;
                default:
//                    log.error("未知数据类型: {}", type);
                    break;
            }
        } catch (Exception e) {
//            log.error("处理消息时发生错误: {}", e.getMessage());
        } finally {
            // 确认消息消费
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (Exception e) {
//                log.error("确认消息时发生错误: {}", e.getMessage());
            }
        }
    }

    private void handleLocationData(String data) {
        JSONObject locationJsonObj = JSONUtil.parseObj(data);
        String longitude = locationJsonObj.getStr("longitude");
        String latitude = locationJsonObj.getStr("latitude");
        String position = createPosition(longitude, latitude);
        String imei = locationJsonObj.getStr("imei");
    }

    private String createPosition(String longitude, String latitude) {

        return longitude + "," + latitude;
    }

    private void handleMessageData(String data) {
        JSONObject messageJson = JSONUtil.parseObj(data);
        String messageType = messageJson.getStr("type");
        if (MESSAGE_SAFE.equals(messageType) || MESSAGE_SOS.equals(messageType)) {
            String location = messageJson.getStr("location");
            handleLocationData(location);
        } else {
//            log.warn("不支持的消息类型: {}", messageType);
        }
    }
}
